package com.online.fund.spider;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.online.fund.spider.dao.FundDao;
import com.online.fund.spider.entity.FundShares;
import com.online.fund.util.HttpClientUtil;

import jdk.nashorn.api.scripting.ScriptObjectMirror;

@Service
@SuppressWarnings("restriction")
public class FundSharesProcesser {
	
	private final static Logger logger = LoggerFactory.getLogger(FundSharesProcesser.class);
			
	@Resource
	private FundDao fundDao;
	
	private final static String FUND_PAGE_URL = "http://fund.eastmoney.com/f10/FundArchivesDatas.aspx?type=jjcc&code=#{CODE}&topline=10&year=&month=&rt=0.03171087342476042";

	public void parsePage(String fundCode, String fundName) {
		parsePage(fundCode, fundName, true);
	}
	
	public void parsePage(String fundCode, String fundName, boolean saveFlag) {
		try {
			String resultStr = HttpClientUtil.httpGetRequest(FUND_PAGE_URL.replace("#{CODE}", fundCode));
			
			ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
			ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
			nashorn.eval(resultStr);
			ScriptObjectMirror db = (ScriptObjectMirror) nashorn.get("apidata");
			String content = (String) db.get("content");
			if (!"".equals(content)) {
				Document doc = Jsoup.parse(content);
//				System.out.println(content);
				
				List<FundShares> list = new ArrayList<FundShares>();
				
				for (int i = 0 ; i < doc.select("div.box").size(); i++) {
					// 统计日期(截止日期)
					String statisticsDate = doc.select("div.box").get(i).select("font.px12").get(0).text();
					Elements tableElements = doc.select("div.box").get(i).select("table.w782 tr");
					for (Element trElement : tableElements) {
						Elements tdElements = trElement.select("td");
						if (tdElements.size() == 0) {
							continue;
						}
						
						FundShares fundShares = new FundShares();
						fundShares.setFundCode(fundCode);
						fundShares.setFundName(fundName);
						fundShares.setStatisticsDate(statisticsDate);
						
						fundShares.setNumIndex(Integer.parseInt(tdElements.get(0).text().replace("*", "")));
						fundShares.setSharesCode(tdElements.get(1).text());
						fundShares.setSharesName(tdElements.get(2).text());
						if (i == 0) {
							String netValueRate = tdElements.get(6).text().replace("%", "");
							if (netValueRate != null && !netValueRate.contains("-")) {
								fundShares.setNetValueRate(Double.parseDouble(netValueRate));
							}
							
							String numberOfShares = tdElements.get(7).text().replaceAll(",", "");
							if (numberOfShares != null && !numberOfShares.contains("-")) {
								fundShares.setNumberOfShares(Double.parseDouble(numberOfShares));
							}

							String marketValue = tdElements.get(8).text().replaceAll(",", "");
							if (marketValue != null && !marketValue.contains("-")) {
								fundShares.setMarketValue(Double.parseDouble(marketValue));
							}
						} else {
							String netValueRate = tdElements.get(4).text().replace("%", "");
							if (netValueRate != null && !netValueRate.contains("-")) {
								fundShares.setNetValueRate(Double.parseDouble(netValueRate));
							}
							
							String numberOfShares = tdElements.get(5).text().replaceAll(",", "");
							if (numberOfShares != null && !numberOfShares.contains("-")) {
								fundShares.setNumberOfShares(Double.parseDouble(numberOfShares));
							}

							String marketValue = tdElements.get(6).text().replaceAll(",", "");
							if (marketValue != null && !marketValue.contains("-")) {
								fundShares.setMarketValue(Double.parseDouble(marketValue));
							}
						}
						
						
//						System.out.println(fundShares);
						
						list.add(fundShares);
					}
					
					if (saveFlag) {
						//fundDao.deleteFundShares(fundCode, statisticsDate);
						if (fundDao.countFundShares(fundCode, statisticsDate) == 0) {
							fundDao.batchAddFundShares(list);
						}
					} else {
						System.out.println(list);
					}
					list.clear();
				}
			}
			
		} catch (Exception e) {
			logger.error(fundCode, e);
		}
		
	}
	
	public static void main(String[] args) throws Exception {
		FundSharesProcesser fundSharesProcesser = new FundSharesProcesser();
		fundSharesProcesser.parsePage("001915", "宝盈医疗健康沪港深股票", false);
	}
}
